package thread;

import java.util.Map;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;

class MyBlockingQueue {
    int [] array = new int[100];//定义一个数组为队列
    int head = 0;//队头下标
    int tail = 0;//队尾下标
    int size = 0;//元素个数

    //模拟实现 put 方法
    synchronized public void put(int value) throws InterruptedException {
        if (size == array.length) {
            this.wait();//队列已满设为阻塞状态
        }
        array[tail] = value;//把value值放在数组对应下标中
        tail++;//队尾下表自增
        size++;//元素个数自增
        if (tail == array.length) {
            tail = 0;//队尾下标重置为0
        }
        this.notify();//唤醒队列空的阻塞状态
    }

    //模拟实现 take 方法
    synchronized public int take() throws InterruptedException {
        if (size == 0){
            this.wait();//队列已空设为阻塞状态
        }
        int value = array[head];//队头元素负责个value
        head++;//队头下标往后自增
        size--;//元素个数自减
        if (head == array.length) {
            head = 0;//对头下标置为0
        }
        this.notify();//唤醒队列满的阻塞状态
        return value;//返回队头元素
    }
}
public class ThreadDemo2 {
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue();
        //生产者
        Thread thread1 = new Thread(()-> {
            int i = 1;
            while (true) {
                try {
                    System.out.println("生产者: "+i);
                    myBlockingQueue.put(i);
                    i++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();
        //消费者
        Thread thread2 = new Thread(()-> {
            while (true) {
                try {
                    int i = myBlockingQueue.take();
                    System.out.println("消费者: "+i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread2.start();
    }
}
